package com.small.nacos.config.server.service.dump.processor;

import small.common.crypto.util.KeyUtil;
import com.small.nacos.api.config.model.ConfigInfo;
import com.small.nacos.common.task.NacosTask;
import com.small.nacos.common.task.NacosTaskProcessor;
import com.small.nacos.config.server.model.event.ConfigDumpEvent;
import com.small.nacos.config.server.service.dump.DumpConfigHandler;
import com.small.nacos.config.server.service.dump.DumpService;
import com.small.nacos.config.server.service.dump.task.DumpTask;
import com.small.nacos.config.server.service.responsitory.PersistService;

import java.util.Objects;

public class DumpProcessor implements NacosTaskProcessor {

    private final DumpService dumpService;

    public DumpProcessor(DumpService dumpService) {
        this.dumpService = dumpService;
    }

    @Override
    public boolean process(NacosTask task) {
        PersistService persistService = dumpService.getPersistService();
        DumpTask dumpTask = (DumpTask) task;
        String[] pair = KeyUtil.parseKey(dumpTask.getGroupKey());
        String dataId = pair[0];
        String group = pair[1];
        String tenant = pair[2];
        long lastModified = dumpTask.getLastModified();
        ConfigDumpEvent.ConfigDumpEventBuilder build = ConfigDumpEvent.builder().namespaceId(tenant).dataId(dataId)
                .group(group).lastModifiedTs(lastModified);
        ConfigInfo cf = persistService.findConfigInfo(dataId, group, tenant);
        build.remove(Objects.isNull(cf));
        build.content(Objects.isNull(cf) ? null : cf.getContent());
        build.type(Objects.isNull(cf) ? null : cf.getType());

        return DumpConfigHandler.configDump(build.build());
    }
}
